package com.egao.gzh.controller;


import com.egao.common.core.Constants;
import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.damon.utils.HttpsUtils;
import com.egao.common.core.exception.GlobalExceptionHandler;
import com.egao.common.core.security.JwtUtil;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.common.system.service.LoginRecordService;
import com.egao.common.system.service.UserService;
import com.egao.gzh.service.Wxservice;
import com.egao.gzh.utils.AesException;
import com.egao.gzh.utils.WXPublicConstants;
import com.egao.gzh.utils.WXPublicUtils;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * api登录相关接口
 * Created by lining on 2019-05-29 下午 3:43.
 * http://localhost/swagger-ui.html
 * http://192.168.1.110/swagger-ui.html
 */
@RequestMapping("/api/nt/wx")
@RestController
@Api(value = "登录Api", tags = {"登录Api"})
public class WxController extends BaseController {

  @Autowired
  private Wxservice wxservice;
  @Autowired
  private UserService userService;
  @Autowired
  private LoginRecordService loginRecordService;

  /**
   * 微信公众平台token
   * 服务器地址(URL)  本地用        http://5rayz9.natappfree.cc/api/nt/login/gzh
   * 服务器地址(URL)  正式服务器用   http://gzh.sszgjzx.com
   */
  @ApiOperation(value = "微信公众平台token", notes = "" +
      "signature 公众号加密签名\n" +
      "timestamp 公众号时间戳\n" +
      "nonce 公众号随机数字\n" +
      "echostr 公众号随机字符串\n" +
      "", httpMethod = "GET")
  @GetMapping("/gzh")
  public String gzhValidate(String signature, String timestamp,
                            String nonce, String echostr) throws AesException {
    if (WXPublicUtils.verifyUrl(signature, timestamp, nonce)) {
      System.out.println("公众号验证成功!");
      return echostr;
    }
    return null;
  }

  @PostMapping(value = "gzh")
  public void processMsg(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    // 调用核心服务类接收处理请求
    Map<String, String> requestMap = wxservice.parseRequest(request.getInputStream());
    System.out.println(requestMap);
    //准备回复的数据包
    String resXml = wxservice.getRespose(requestMap);
//                "<xml>" +
//                "<ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName>" +
//                "<FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName>" +
//                "<CreateTime>"+ System.currentTimeMillis()/1000 +"</CreateTime>" +
//                "<MsgType><![CDATA[text]]></MsgType>" +
//                "<Content><![CDATA[why?]]></Content>" +
//                "</xml>";

    PrintWriter out = response.getWriter();
    System.out.println(resXml);
    out.print(resXml);
    out.flush();
    out.close();
//        ServletInputStream is = request.getInputStream();
//        byte[] b = new byte[1024];
//        int len;
//        StringBuilder sb = new StringBuilder();
//        while ((len=is.read(b))!=-1) {
//            sb.append(new String(b, 0, len));
//        }
  }



  @GetMapping(value = "getGzhOauth")
  public void getGzhOauth(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String path = WXPublicConstants.JAVA_URL+"/api/nt/wx/getGzhCode";

    path = URLEncoder.encode(path, "UTF-8");
    String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+
            WXPublicConstants.APPID +"&redirect_uri="
            + path
            + "&response_type=code&scope=snsapi_base#wechat_redirect";
    response.sendRedirect(url);
  }


  @GetMapping(value = "getGzhCode")
  public void getGzhCode(HttpServletRequest request, HttpServletResponse response) {
    String code = request.getParameter("code");
    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    url = url.replace("APPID", WXPublicConstants.APPID).replace("SECRET", WXPublicConstants.APPSECRET)
            .replace("CODE", code);
    String ret = null;
    ret = HttpsUtils.get2(url);
//    System.out.println(ret);

    JSONObject obj = JSONObject.fromObject(ret);
//    String at = obj.getString("access_token");
//    String openid = obj.getString("openid");
//    url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//    url = url.replace("ACCESS_TOKEN",at).replace("OPENID",openid);
//    ret = HttpsUtils.get2(url);
//    JSONObject obj = JSONObject.fromObject(ret);
    login(obj, request, response);
  }

  public void login(JSONObject obj, HttpServletRequest request, HttpServletResponse response) {
    User user = new User();
    user.setGzhId(obj.getString("openid"));
    try {
      user = userService.getByGzhId(user);
    } catch (EmptyResultDataAccessException e) {
    }
//    user.setNickname(obj.getString("nickname"));
      user.setSex(1);
//    user.setCity(obj.getString("city"));
//    user.setProvince(obj.getString("province"));
//    user.setCountry(obj.getString("country"));
//    user.setAvatar(obj.getString("headimgurl"));

    if (user.getUserId() != null) {
      userService.update2(user);
    } else {
      // 添加到数据库
      List<Integer> roleids = new ArrayList<>();
      roleids.add(WXPublicConstants.NORMAL_USER);
      //新增的用户都为普通游客
      user.setRoleIds(roleids);
      user.setUsername(System.currentTimeMillis()+"");
      user.setPassword(UserConstant.DEFAULT_PSW);
      userService.save2(user);
    }
    String access_token = JwtUtil.buildToken(user.getUsername(), Constants.TOKEN_EXPIRE_TIME, Constants.TOKEN_KEY);
    // 记录登录日志
    loginRecordService.saveAsync(user.getUsername(), 0, "", request);

    String url = "http://"+WXPublicConstants.GZH_URL+"?access_token="+access_token;
    try {
      response.sendRedirect(url);
    } catch (IOException e) {
    }
//    return JsonResult.ok("登录成功").put("access_token", access_token);
//    .put("openId", obj.getString("openid")).put("userinfo", user)
  }

}
